package com.example.wumeng.scangundemo;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.widget.TextView;


import com.chice.scangun.ScanGun;
import com.example.wumeng.scangundemo.utils.ColorUtils;
import com.example.wumeng.scangundemo.widget.SingleToast;


public class MainActivity extends AppCompatActivity {

    private static final String TAG = MainActivity.class.getSimpleName();

    private boolean isHandleKey = true;

    private ScanGun mScanGun = null;

    private TextView tvScanResult; // 扫描结果

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        tvScanResult = findViewById(R.id.tvScanResult);

        // 设置key事件最大间隔,默认20ms,部分低端扫描枪效率低
        ScanGun.setMaxKeysInterval(50);

        mScanGun = new ScanGun(new ScanGun.ScanGunCallBack() {
            @Override
            public void onScanFinish(String s) {
                SingleToast.showToast(s, MainActivity.this);
                tvScanResult.setText(s);
                tvScanResult.setTextColor(ColorUtils.getRandomColorInt());
            }
        });

    }

    /**
     * 监听物理按键
     *
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode <= 6) {
            return super.dispatchKeyEvent(event);
        }
        if (mScanGun.isMaybeScanning(keyCode, event)) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        // 拦截物理键盘事件
        if (isHandleKey && event.getKeyCode() > 6) {

            if (event.getAction() == KeyEvent.ACTION_DOWN) {
                this.onKeyDown(event.getKeyCode(), event);
                return true;
            } else if (event.getAction() == KeyEvent.ACTION_UP) {
                this.onKeyUp(event.getKeyCode(), event);
                return true;
            }
            return true;
        }
        return super.dispatchKeyEvent(event);
    }

}
